import axios from "axios"
import { baseUrl } from "../config";
import { getToken } from "../utils/auth";
// import { Toast,Dialog } from "vant";
import { useStore } from "vuex";
//创建axios实例
const service = axios.create({
	baseURL: baseUrl,  //请求路径
	timeout: 5000      //请求超时时间
})

//请求拦截器
service.interceptors.request.use(
	config => {
		if (getToken()) {
			//让每次请求都携带token
			config.headers['X-Token'] = getToken()
		}
		return config
	},
	error => {
		// 处理请求错误
		console.log(error) // 用于调试
		return Promise.reject(error)
	}
)

//响应拦截器
service.interceptors.response.use(
	response => {
		const res = response.data
		if (res.code !== 200) {
			if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
				useStore().dispatch('user/resetToken').then(() => {
					location.reload()
				})
			}
			return Promise.reject(new Error(res.message || 'Error'))
		} else {
			return res
		}
	},
	error => {
		console.log('err' + error) // 用于调试
		// Toast(error.message||'Error')
		return Promise.reject(error)
	}
)

export default service